package org.jeecg.config.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * http host头攻击漏洞处理过滤器，
 * 需要在配置文件添加allowed.servernames可访问host白名单，
 * 多个host用逗号隔开，本地开发使用127.0.0.1,localhost
 * @author liufr
 */
@Component
public class HostFilter implements Filter{
    /**
     * 自定义实现host白名单添加
     */
    @Value("${allow.servernames}")
    private String ALLOWED_SERVERNAMES;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * host拦截
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // String host = request.getHeader("host");
        String serverName = request.getServerName();
        if (!isEmpty(serverName)) {
            if (checkBlankList(serverName)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                // response.getWriter().print("host deny");
                response.setStatus(403);
                response.flushBuffer();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {
    }

    /**
     * 校验当前host是否在白名单中
     */
    private boolean checkBlankList(String serverName) {
        String[] allowdServerName = ALLOWED_SERVERNAMES.split(",");
        List<String> serverNameList = Arrays.asList(allowdServerName);
        for(String str : serverNameList){
            if(!isEmpty(str) && str.equals(serverName)){
                return true;
            }
        }
        return false;
    }

    /**
     * 判空
     */
    public boolean isEmpty(Object str) {
        return str == null || "".equals(str);
    }


}
